package chixing.day20.work3;

import java.util.*;

public class ContractService {
    private List<Contract> contracts;

    public ContractService() {
        this.contracts = new ArrayList<>();
    }

    public ContractService(List<Contract> contracts) {
        this.contracts = contracts;
    }

    // 提交审批
    public void submitForApproval(int contractId) {
        for (Contract contract : contracts) {
            if ((contract.getContractId())==contractId){
                contract.setContractStatus(ContractStatus.PENDING_APPROVAL);
                System.out.println("合同 " + contractId + " 提交审批，状态: " + ContractStatus.PENDING_APPROVAL);
                return;
            }
        }
        System.out.println("未找到合同 ID: " + contractId);
    }

    // 审批通过
    public void approve(int contractId) {
        for (Contract contract : contracts) {
            if ((contract.getContractId())==contractId) {
                contract.setContractStatus(ContractStatus.APPROVED);
                System.out.println("合同 " + contractId + " 审批通过，状态: " + ContractStatus.APPROVED);
                return;
            }
        }
        System.out.println("未找到合同 ID: " + contractId);
    }

    // 拒绝合同
    public void reject(int contractId) {
        for (Contract contract : contracts) {
            if ((contract.getContractId())==contractId) {
                contract.setContractStatus(ContractStatus.REJECTED);
                System.out.println("合同 " + contractId + " 被拒绝，状态: " + ContractStatus.REJECTED);
                return;
            }
        }
        System.out.println("未找到合同 ID: " + contractId);
    }

    // 根据状态获取合同列表
    public List<Contract> getContractsByStatus(ContractStatus status) {
        List<Contract> result = new ArrayList<>();
        for (Contract contract : contracts) {
            if (contract.getContractStatus() == status) {
                result.add(contract);
            }
        }
        return result;
    }

    // 计算部门合同总金额
    public double totalAmountByDepartment(String dept) {
        double total = 0;
        for (Contract contract : contracts) {
            if (dept.equals(contract.getDepartment())) {
                total += contract.getContractAmount();
            }
        }
        return total;
    }

    // 按供应商分组合同
    public Map<String, List<Contract>> groupBySupplier() {
        Map<String, List<Contract>> grouped = new HashMap<>();
        for (Contract contract : contracts) {
            String supplier = contract.getSupplier();
            if (!grouped.containsKey(supplier)) {
                grouped.put(supplier, new ArrayList<>());
            }
            grouped.get(supplier).add(contract);
        }
        return grouped;
    }

    // 添加合同
    public void addContract(Contract contract) {
        contracts.add(contract);
    }

    // 获取所有合同
    public List<Contract> getContracts() {
        return contracts;
    }
}

